<template>
  <div class="container" :class="{'darkmode' : isDarkmode}">
    <!-- 左侧开始 -->
    <div class="left">
      <div class="left-top">
        <el-input
          style="width: 240px"
          size="large"
          placeholder="查询历史记录"
          :suffix-icon="Search"
          v-model="inputValue"
          clearable
        />
      </div>
      <div class="left-bottom">
        <el-menu
          default-active="2"
          class="el-menu-vertical-demo"
          @open="handleOpen"
          @close="handleClose"
          v-for="month in historyData.monthList"
          :key="month.timeString"
        >
          <el-sub-menu index="1">
            <template #title>
              <el-icon><Folder /></el-icon>
              <span>{{historyData.timeString}}年{{month.timeString}}月</span>
            </template>
            <el-menu-item @click="handleClickDay(day, month.timeString)" v-for="day in month.dayList" :key="day.timeString" index="{{day.timeString}}"><el-icon><Document /></el-icon>第{{day.timeString}}天</el-menu-item>
          </el-sub-menu>
        </el-menu>
      </div>
    </div>
    <!-- 左侧结束 -->
    <!-- 右侧开始 -->
    <div class="right">
      <div class="right-top">
        <div class="right-top-title">历史记录</div>
        <div class="right-top-clear">
          <el-icon><DeleteFilled /></el-icon>
          <span @click="handleClearAll" style="margin-left: 10px;">清除历史</span>
        </div>
      </div>
      <!-- 单天展示 -->
      <div v-if="isOneDay === 1" class="right-bottom">
        <el-card style="max-width: 100%; margin: 20px 80px;">
          <template #header>
            <div class="card-header">
              <span>{{historyData.timeString}}-{{monthToDay}}-{{dayData.timeString}}</span>
              <div class="card-header-right">
                <el-checkbox v-model="dayData.status" @click="handleCheckAllChange(dayData)">
                  全选
                </el-checkbox>
                <el-button v-if="dayData.status" type="danger" size="small" @click="hanleAllDelete">批量删除</el-button>
              </div>
            </div>
          </template>
          <div class="card-content">
            <p class="card-content-row" v-for="h in dayData.historyList" :key="h.id">
              <span class="card-content-row-head">
                <el-checkbox v-model="h.status" @click="handleCheckChange(h)">
                </el-checkbox>
                <span @click="handleSkip(h.url)" class="card-content-row-head-data">
                  {{ h.title }}
                </span>
              </span>
              <el-button @click="handleCheckRow(h.id, 1)" type="danger" size="small">删除</el-button>
            </p>
          </div>
        </el-card>
      </div>
      <!-- 默认展示 -->
      <div v-else-if="isOneDay === 2" class="right-bottom" v-for="month in historyData.monthList" :key="month.timeString">
        <el-card style="max-width: 100%; margin: 20px 80px;" v-for="day in month.dayList" :key="day.timeString">
          <template #header>
            <div class="card-header">
              <span>{{historyData.timeString}}-{{month.timeString}}-{{day.timeString}}</span>
              <div class="card-header-right">
                <el-checkbox v-model="day.status" @click="handleCheckAllChange(day)">
                  全选
                </el-checkbox>
                <el-button v-if="day.status" type="danger" size="small" @click="hanleAllDelete">批量删除</el-button>
              </div>
            </div>
          </template>
          <div class="card-content">
            <p class="card-content-row" v-for="h in day.historyList" :key="h.id">
              <span class="card-content-row-head">
                <el-checkbox v-model="h.status" @click="handleCheckChange(h)">
                </el-checkbox>
                <span @click="handleSkip(h.url)" class="card-content-row-head-data">
                  {{ h.title }}
                </span>
              </span>
              <el-button @click="handleCheckRow(h.id, 2)" type="danger" size="small">删除</el-button>
            </p>
          </div>
        </el-card>
      </div>
      <!-- 搜索展示 -->
      <div v-else-if="isOneDay === 3" class="right-bottom">
        <el-card style="max-width: 100%; margin: 20px 80px;">
          <template #header>
            <div class="card-header">
              <span style="color: #409EFF;">对应搜索结果如下所示</span>
              <div class="card-header-right">
                <el-checkbox v-model="searchData.status" @click="handleCheckAllSearchDataChange(searchData)">
                  全选
                </el-checkbox>
                <el-button v-if="searchData.status" type="danger" size="small" @click="hanleAllDelete">批量删除</el-button>
              </div>
            </div>
          </template>
          <div class="card-content">
            <p class="card-content-row" v-for="s in searchData.historyList" :key="s.id">
              <span class="card-content-row-head">
                <el-checkbox v-model="s.status" @click="handleCheckChange(s)">
                </el-checkbox>
                <span @click="handleSkip(s.url)" class="card-content-row-head-data">
                  {{ s.title }}
                </span>
              </span>
              <el-button @click="handleCheckRow(s.id, 3)" type="danger" size="small">删除</el-button>
            </p>
          </div>
        </el-card>
      </div>
      <!-- 没有记录时 -->
      <div v-else-if="isOneDay === 4" class="right-bottom">
        <el-card style="max-width: 100%; margin: 20px 80px;">
          <template #header>
            <div class="card-header">
              <span>没有历史记录哦，去探索一下吧</span>
            </div>
          </template>
        </el-card>
      </div>
    </div>
    <!-- 右侧结束 -->
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted, watch, h } from 'vue'
import { type HistoryData, DayItemImpl, HistoryItemImpl, SearchItemImpl }from '@/types/historyInterface.ts';
import {historyApi} from '@/api/history.js'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Search } from '@element-plus/icons-vue'
import {useRouter} from 'vue-router'

//### 定义数据 ###
const router = useRouter();     //创建对应路由器
const isDarkmode = ref(false);  //是否开启夜间模式
const inputValue = ref('')      //搜索框输入的值
const deleteInBatches = reactive<string[]>([])  //记录批量删除的id集合, 搜索、单天、默认共用
const monthToDay = ref("")    //记录对应一天数据对应的月份
const isOneDay = ref(2)     //决定是否显示一天的数据，或者搜索结果
//对应所有数据
const historyData = reactive<HistoryData>({})
//对应用户点击某一天的数据
const dayData = reactive<DayItemImpl>({
  "status": false,
  "timeString": "28",
  "historyList": [
    {
      "id": "7",
      "title": "Java基础入门——开启编程之旅",
      "websiteIcon": null,
      "url": "/searchDetails?articleId=13",
      "type": 1,
      "status": false,
      "createBy": "2",
      "createTime": "2025-04-28 00:20:51"
    }
  ]
});
//对应用户搜索结果数据
const searchData = ref<SearchItemImpl>({
  "status": false,
  "historyList": [
    {
      "id": "-1",
      "title": "默认数据，当前搜索没有对应匹配内容",
      "websiteIcon": null,
      "url": "/searchDetails?articleId=13",
      "type": 1,
      "status": false,
      "createBy": "2",
      "createTime": "2025-04-28 00:20:51"
    }
  ]
});

//### 定义方法 ###
//页面初始化方法
const pageInitialization = async () => {
  const result = await historyApi.obtainTheCurrentYearsHistoricalRecords();
  console.log(result);
  if(result.code === 200) {
    Object.assign(historyData, result.data);
  }
  
  if(result.code === 500) {
    console.log("看看删除后的初始化数据", result.data); //貌似没运行
    historyData.monthList = [];
    isOneDay.value = 4;
  }
}

pageInitialization();

//对应历史记录实现跳转
const handleSkip = (url:string) => {
  const [path, KeyValue] = url.split("?");
  const [key, value] = KeyValue.split("=");
  router.push({
    path: url,
    query: {
      articleId: value
    }
  });
}

//对应用户点击某一天数据时
const handleClickDay = (day: DayItemImpl, month:string) => {
  isOneDay.value = 1;
  monthToDay.value = month;
  Object.assign(dayData, day);
}

//清空历史
const handleClearAll = async () => {
  ElMessageBox.confirm(
    '你确定清除所有历史记录吗？',
    '警告',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    }
  )
    .then(async () => {
      const result = await historyApi.deleteAll();
      if(result.code === 200) {
        ElMessage({
          type: 'success',
          message: '清除成功',
        })
        pageInitialization();
        isOneDay.value = 2;
      }else {
        ElMessage({
          type: 'error',
          message: '清除失败',
        })
      }
    })
    .catch(() => {
      ElMessage({
        type: 'info',
        message: '清除操作取消或异常',
      })
    })  
}

//删除一条
const handleCheckRow = async (id:string, type:number) => {
  console.log("选中单个", id)
  ElMessageBox.confirm(
    '你确定要删除当前行数据吗?',
    '警告',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    }
  )
    .then(async () => {
      const result =  await historyApi.deleteOneByOne({"id": id});
      if(result.code === 200) {
        ElMessage({
          type: 'success',
          message: '删除成功',
        })
        if(type === 2) {
          pageInitialization(); //重新初始化页面
        }else if(type === 1) {
          const index = dayData.historyList.findIndex(h => h.id === id);
          if (index !== -1) {
            dayData.historyList.splice(index, 1); // 删除第一个匹配项
          }

          if(dayData.historyList.length < 1) {
            pageInitialization();
            type = 2;
          }
        }else if(type === 3) {
          const index = searchData.value.historyList.findIndex(h => h.id === id);
          if (index !== -1) {
            searchData.value.historyList.splice(index, 1); // 删除第一个匹配项
          }

          if(searchData.value.historyList.length < 1) {
            pageInitialization();
            type = 2;
          }
        }
        isOneDay.value = type;
      }else {
        ElMessage({
          type: 'error',
          message: '删除失败',
        })
      }
    })
    .catch(() => {
      ElMessage({
        type: 'info',
        message: '取消成功或者没有传递数据',
      })
    })
}

//批量删除
const hanleAllDelete = () => {
  console.log("当前批量选中的id", deleteInBatches);
  ElMessageBox.confirm(
    '批量选中将删除所有选中的记录，你确定要删除?',
    '警告',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    }
  )
    .then(async () => {
      console.log("我运行了")
      const result = await historyApi.deleteInBatches(deleteInBatches);
      console.log("看看删除返回结果", result)
      if(result.code === 200) {
        ElMessage({
          type: 'success',
          message: '删除成功',
        })
        isOneDay.value = 2; //无论是搜索还是单天，批量删除后默认回到原本页
        pageInitialization();
      }else {
        ElMessage({
          type: 'error',
          message: '删除失败',
        })
      }
    })
    .catch(() => {
      ElMessage({
        type: 'info',
        message: '取消成功或者没有传递数据',
      })
    })  
}

//搜索数据全选
const handleCheckAllSearchDataChange = (searchData: SearchItemImpl) => {
  if(searchData.status) { //取消选中
    searchData.historyList.forEach(s => {
      const index = deleteInBatches.indexOf(s.id);
      if (index !== -1) {
        deleteInBatches.splice(index, 1); // 删除第一个匹配项
      }
      s.status = !searchData.status;
    })
  }else { //选中
    searchData.historyList.forEach(s => {
      if(deleteInBatches.indexOf(s.id) === -1) {
        deleteInBatches.push(s.id);
      }
      s.status = !searchData.status;
    })
  }
  console.log("当前搜索结果选中的数据集合", deleteInBatches);
}

//历史记录全选
const handleCheckAllChange = (day: DayItemImpl) => {
  if(day.status) {  //说明是取消
    day.historyList.forEach(h => {
      const index = deleteInBatches.indexOf(h.id);
      if (index !== -1) {
        deleteInBatches.splice(index, 1); // 删除第一个匹配项
      }
      h.status = !day.status;
    })
  }else { //说明是选中
    day.historyList.forEach(h => {
      if(deleteInBatches.indexOf(h.id) === -1) {
        deleteInBatches.push(h.id);
      }
      h.status = !day.status;
    })
  }
  console.log("当前选中的数据集合", deleteInBatches);
}

//历史记录单选，有时全选后想要取消其中几个
const handleCheckChange = (history: HistoryItemImpl) => {
  if(history.status) {  //是取消
    const index = deleteInBatches.indexOf(history.id);
    if (index !== -1) {
      deleteInBatches.splice(index, 1); // 删除第一个匹配项
    }
  }else {
    deleteInBatches.push(history.id);
  }
  console.log("当前选中的数据集合", deleteInBatches);
}

//菜单栏的回调函数
const handleOpen = (key: string, keyPath: string[]) => {
  console.log(key, keyPath)
}
const handleClose = (key: string, keyPath: string[]) => {
  console.log(key, keyPath)
}

//### 监听方法 ###
watch(inputValue, async (newVal, oldVal) => {
  if(isOneDay.value === 4) {
    ElMessage({
      type: 'info',
      message: '当前用户没有历史记录',
    })
    return;
  }

  if(newVal === "") { //没有搜索显示默认的数据
    isOneDay.value = 2;
  }else {
    console.log('输入值发生变化:', newVal);
    const result = await historyApi.searchHistoryByTitle({"title": newVal});
    if(result.code === 200) {
      // console.log("看看", result)
      searchData.value = result.data;
    }
    isOneDay.value = 3;
  }
});

//### 生命周期函数 ###
onMounted(() => {
  //夜间模式检查
  let darkmode = window.localStorage.getItem('tenSeekIsDarkmode');
  if(darkmode === 'true') {
    isDarkmode.value = true;
  }
})
</script>


<style scoped lang="scss">
.container {
  // background: antiquewhite;
  display: flex;
  height: 85vh;

  // margin: 10px 0px;

  .left {
    // background: red;
    flex: 2;
    padding: 10px;

    .left-top {
      margin-bottom: 10px;

      /* 搜索框 */
      ::v-deep .el-input__wrapper {
        background: var(--base-color);
      }

      /* 搜索框内部文字 */
      ::v-deep .el-input__inner {
        color: var(--text-color);
      }
    }

    .left-bottom {

      ::v-deep .el-menu {
        background: var(--base-color);
      }

      ::v-deep .el-sub-menu__title {
        color: var(--text-color);
      }

      ::v-deep .el-menu-item {
        color: var(--text-color);
      }
    }

  }

  .right {
    // background: blue;
    flex: 8;
    overflow-x: auto;
    
    .right-top {
      display: flex;
      justify-content: space-between; /* 使子项在主轴上两端分布 */
      align-items: center;  /* 复轴居中 */
      margin: 10px 80px 0px;
      box-shadow: 0 4px 8px 0 rgba(0, 0, 0, 0.2), 0 6px 20px 0 rgba(0, 0, 0, 0.19);
      border-radius: 4px;
      height: 30px;

      .right-top-title {
        // background: chartreuse;
        border-radius: 4px 0px 0px 4px;
        padding-left: 20px;
        font-weight: bold;
      }

      .right-top-clear {
        // background: chartreuse;
        border-radius: 0px 4px 4px 0px;
        display: flex;
        align-items: center;  /* 复轴居中 */
        padding-right: 20px;
      }
    }

    .right-bottom {

      .card-header {
        display: flex;
        flex-direction: row; /* 保持主轴为水平方向 */
        justify-content: space-between; /* 使子项在主轴上两端分布 */

        .card-header-right {
          display: flex;
          align-items: center;  /* 复轴居中 */
          gap: 15px; /* 设置子元素之间的间距 */
        }
      }

      .card-content {

        .card-content-row {
          display: flex;
          flex-direction: row; /* 保持主轴为水平方向 */
          justify-content: space-between; /* 使子项在主轴上两端分布 */

          .card-content-row-head {

            .card-content-row-head-data {
              margin-left: 15px;
            }
          }
        }
      }
    }
  }
}

</style>